package com.qhy.springcloud.service.impl;

import com.qhy.springcloud.dao.OrderMapper;
import com.qhy.springcloud.domain.CommonResult;
import com.qhy.springcloud.domain.Order;
import com.qhy.springcloud.service.AccountService;
import com.qhy.springcloud.service.OrderService;
import com.qhy.springcloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author qiuhongyu
 * @date 2020/12/7 15:37
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StorageService storageService;

    @Autowired
    private AccountService accountService;

    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     *
     * @param order
     */
    @GlobalTransactional(name = "qhy-create-order", rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("---->开始创建订单");
        //1 新建订单
        orderMapper.create(order);

        log.info("---->订单微服务开始调用库存，做扣减数量");
        //2 扣减库存
        CommonResult decrease = storageService.decrease(order.getProductId(), order.getOrderCount());
        log.info("---->订单微服务开始调用库存，做扣减end");

        log.info("---->订单微服务开始调用账户，做扣减Money");
        //3 扣减账户余额
        CommonResult decrease1 = accountService.decrease(order.getUserId(), order.getMoney());
        log.info("---->订单微服务开始调用账户，做扣减end");

        //修改订单的状态，从0到1，1代表已经完成
        log.info("---->修改订单状态开始");
        orderMapper.update(order.getUserId(), 0);
        log.info("---->修改订单状态end");

        log.info("---->下订单结束了***********");
    }
}
